<template>
	<view>

    <!-- 提交搜索弹窗 -->
    <u-popup
        :show="condition.show"
        :round="10"
        mode="bottom"
        :direction=0
        :closeable=true
        @close="condition.close()"
    >
      <view>
        <view style="text-align: center;margin: 10px 0 20px 0 ">
          <text style="font-size: 34rpx;font-weight: bold">
            填充筛选条件(不填的条件不参与判断)
          </text>
        </view>
        <view style="margin: 10px 10px">
          <u--form labelPosition="left" labelWidth="auto">
            <u-form-item label="区域ID:">
              <u--input
                  v-model="condition.data.regionId"
                  :clearable=true
                  border="bottom"
                  type="number"
              >
              </u--input>
            </u-form-item>

            <u-form-item label="标题包含:">
              <u--input
                  v-model="condition.data.title"
                  :clearable=true
                  border="bottom"
              >
              </u--input>
            </u-form-item>

            <u-form-item label="商品分类:">
              <u-tag
                  :text=options.goodsCategory.text
                  plain
                  size="large"
                  type="success"
                  @click="options.goodsCategory.open"
              ></u-tag>
              <u-icon slot="right" name="arrow-right"></u-icon>
            </u-form-item>

            <u-form-item label="创建时间范围:">
              <view style="z-index:10000">
                <uni-datetime-picker
                    hide-second="true"
                    type="datetimerange"
                    v-model="condition.data.createTime.value"
                    @change="condition.data.createTime.change"
                    rangeSeparator="至" />
              </view>
            </u-form-item>

            <view>
              <u-row gutter="1">
                <u-col :span="6">
                  <u-button type="success" text="清空" @click="condition.def()"></u-button>
                </u-col>
                <u-col :span="6">
                  <u-button type="primary" text="搜索" @click="condition.search()"></u-button>
                </u-col>
              </u-row>
            </view>
          </u--form>
        </view>
      </view>
    </u-popup>

    <view>
      <view style="margin: 20rpx 0 0 20rpx">
        <view style="display: inline-block;margin-right: 10rpx">
          <u-button shape="circle" size="medium" @click="condition.open()">
            <text style="font-size: 24rpx;
            font-weight: bold;
            color: #8c7d7d;padding: 0 20rpx">
              条件搜索
            </text>
          </u-button>
        </view>

        <view style="display: inline-block;margin-right: 10rpx">
          <u-button shape="circle" size="medium" @click="listSortPicker.open()">
            <text style="font-size: 24rpx;
            font-weight: bold;
            color: #8c7d7d;padding: 0 20rpx">
              表格排序
            </text>
          </u-button>
        </view>
      </view>

    </view>

    <!--商品分类选择器-->
    <u-picker
        :show="options.goodsCategory.show"
        :columns="options.goodsCategory.ops"
        @confirm="options.goodsCategory.confirm"
        @close="options.goodsCategory.close"
        @cancel="options.goodsCategory.close"
        closeOnClickOverlay="true"
        title="选择商品分类"
        keyName="name"
    >
    </u-picker>


    <!--悬浮按钮-->
    <uni-fab ref="fab"
             :pattern="fab.pattern"
             :content="fab.content"
             :horizontal="fab.horizontal"
             :vertical="fab.vertical"
             :direction="fab.direction"
             @trigger="fab.trigger"
    />

    <!-- 排序条件选择器 -->
    <u-picker
        :show="listSortPicker.show"
        :columns="listSortPicker.options"
        @confirm="listSortPicker.confirm"
        @close="listSortPicker.close"
        @cancel="listSortPicker.close"
        title="选择某属性点击确定即可"
        :closeOnClickOverlay=true
        keyName="label"
    >
    </u-picker>

    <!-- 删除商品对话窗 -->
    <uni-popup ref="deleteDialog" type="dialog">
      <uni-popup-dialog
          title="确认删除该商品吗?"
          :before-close="true"
          @close="options.deleteGoodsDialog.close"
          @confirm="options.deleteGoodsDialog.confirm">
      </uni-popup-dialog>
    </uni-popup>

    <!-- 表格 -->
    <view
        style="margin: 20rpx 30rpx"
    >
      <uni-table
          border
          stripe
          :loading=table.loading
          emptyText="您当前还没有果蔬商品噢."
      >
        <!-- 表头行 -->
        <uni-tr>
          <uni-th align="center">
            <text class="table-th-font">区域ID</text>
          </uni-th>

          <uni-th align="center" width="30">
            <text class="table-th-font">主图</text>
          </uni-th>

          <uni-th align="center">
            <text class="table-th-font">标题</text>
          </uni-th>

          <uni-th align="center" width="200">
            <text class="table-th-font">创建时间</text>
          </uni-th>

          <uni-th align="center" width="100">
            <text class="table-th-font">分类</text>
          </uni-th>

          <uni-th align="center" width="100">
            <text class="table-th-font">售卖方式</text>
          </uni-th>

          <uni-th align="center">
            <text class="table-th-font">价格</text>
          </uni-th>

          <uni-th align="center">
            <text class="table-th-font">销量</text>
          </uni-th>

          <uni-th align="center" width="250">
            <text class="table-th-font">操作</text>
          </uni-th>

        </uni-tr>

        <!-- 数据行 -->
        <uni-tr v-for="(item,index) in table.data " :key="index">
          <uni-td align="center">
            <text>{{ item.regionId }}</text>
          </uni-td>
          <uni-td align="center">
            <view style="display: inline-block;line-height: 33px">
              <u-avatar
                  :src=item.avatar
                  size="33"
              ></u-avatar>
            </view>
          </uni-td>
          <uni-td align="center">
            <text id="text-flow">{{ item.title }}</text>
          </uni-td>

          <uni-td align="center">
            <text>{{service.style.time(item.createTime,6)}}</text>
          </uni-td>

          <uni-td align="center">
            <text>{{style.category(item.categoryId)}}</text>
          </uni-td>

          <uni-td align="center">
            <rich-text :nodes="style.type(item.type)"></rich-text>
          </uni-td>

          <uni-td align="center">
            <text v-if="item.type === 1">{{item.growPrice}} 元</text>
            <text v-if="item.type === 0">{{item.price}} 元</text>
            <text v-if="item.type === 2">
              <text>采:{{item.price}}元</text>
              <text style="margin: 0 4px">/</text>
              <text>种:{{item.growPrice}}元</text>
            </text>
          </uni-td>

          <uni-td align="center">
            <text>{{item.sale}}</text>
          </uni-td>

          <uni-td align="center">
            <button
                class="operation-btn"
                type="primary"
                size="mini"
                @click="table.gotoEditor(item.id)"
            >详情</button>
            <button class="operation-btn" type="default" size="mini" @click="updateStatus(item.id,index)">
              <rich-text :nodes="style.getStatusBtn(item.status)"></rich-text>
            </button>
            <button class="operation-btn" type="warn" size="mini"
                    @click="options.deleteGoodsDialog.open(item.id,index)">删除</button>
          </uni-td>
        </uni-tr>
      </uni-table>
    </view>

    <!-- 分页 -->
    <view
        style="text-align: center"
    >
      <view style="display: inline-block;margin: 0 8rpx">
        <page-pagination
            :total="table.total"
            :pageSize="table.pageSize"
            :showAround="true"
            :btnText="true"
            :forceEllipses="true"
            @change="table.setPageNo">
        </page-pagination>
      </view>
    </view>

    <!--自己封装的提示器-->
    <popup ref="popup"/>
	</view>
</template>

<script>
  import popup from "@/merchant/my/my-popup"
  import service from "@/utils/service";
	export default {
    components: {popup},
		data() {
		  let _vm = this;
			return {
			  service: service,
        /* 表格对象 */
        table: {
          loading: true,
          total: 0,
          pageSize: 10,
          pageNo: 1,
          data: [],
          setPageNo(v){
            _vm.table.pageNo = v
            _vm.getList();
          },
          /* 跳转到编辑页面 */
          gotoEditor(id){
            let data = JSON.stringify({target: 'update', id: id})
            uni.navigateTo({
              url: 'editor?param=' + data,
            })
          }
        },
        // 表格排序选择器
        listSortPicker:{
          show: false,
          // 排序字段
          sortKey: null,
          // 排序规则 1 正序 -1 倒序
          sort: -1,
          options: [
            [
              {label: '默认', key: null},
              {label: '销量', key: 'sale'},
              {label: '创建时间', key: 'create_time'},
            ],
            [
              {label: '从小到大', value: 1},
              {label: '从大到小', value: -1},
            ],
          ],
          // 确认回调
          confirm(v){
            let me = _vm.listSortPicker;
            console.log("表格排序选项结果 : ", v)
            me.show = false;
            // 默认
            if (v.value[0].key === null) {
              me.sort = v.value[1].value;
            }else{
              me.sortKey = v.value[0].key;
            }
            me.sort = v.value[1].value;
            this.getList();
          },
          close(){
            _vm.listSortPicker.show = false;
          },
          open(){
            _vm.listSortPicker.show = true;
          }
        },
        /*悬浮按钮对象*/
        fab:{
          title: 'uni-fab',
          directionStr: '垂直',
          horizontal: 'right',
          vertical: 'top',
          direction: 'horizontal',
          pattern: {
            color: '#f30505',
            backgroundColor: '#fc080800',
            selectedColor: '#fc2752',
            buttonColor: '#36d64645',
            iconColor: '#fff'
          },
          is_color_type: false,
          content: [
            {
              iconPath: 'https://s1.chu0.com/src/img/png/03/03d5b786444844a5a424c143dba43b32.png?imageMogr2/auto-orient/thumbnail/!234x234r/gravity/Center/crop/234x234/quality/85/&e=1735488000&token=1srnZGLKZ0Aqlz6dk7yF4SkiYf4eP-YrEOdM1sob:e32FjXBL3nT7cRQXCcdByMM5-MQ=',
              selectedIconPath: 'https://s1.aigei.com/src/img/png/39/3977b149ad9f4565ab630d98f33a98b7.png?imageMogr2/auto-orient/thumbnail/!234x234r/gravity/Center/crop/234x234/quality/85/&e=1735488000&token=P7S2Xpzfz11vAkASLTkfHN7Fw-oOZBecqeJaxypL:6xu3wgiuYq2BGyMxHYN1nHA2c_M=',
              text: '添加果蔬',
              active: false,
            },
          ],
          trigger(v){
            console.log("悬浮标签点击回调 :" ,v);
            if(v.index === 0){
              let data = JSON.stringify({target: 'add'});
              uni.navigateTo({
                url: 'editor?param='+data,
              })
            }
          }
        },
        /* 样式对象*/
        style:{
          /* 售卖方式 */
          type(v){
            switch (v) {
              case 0:
                return "<span style='color: #2ecc71'>采摘</span>"
              case 1:
                return "<span style='color: #16a085'>种植</span>"
              case 2:
                return "<span style='color: #00cec9'>采种</span>"
            }
          },
          /* 商品分类 */
          category(id){
            if(_vm.options.goodsCategory === 0){
              return "获取失败";
            }
            let obj = _vm.options.goodsCategory.ops[0].find(e =>{
              return e.id === id;
            })
            return obj.name;
          },
          /* 上下架状态 */
          getStatusBtn(status){
            switch(status){
              case 0:
                return "<span style='color: #ff6b81'>下架</span>"
              case -1:
                return "<span style='color: #1e90ff'>上架</span>"
            }
          }
        },
        /* 选项对象 */
        options:{
          /* 商品分类 */
          goodsCategory:{
            show: false,
            text: "点击选择商品分类",
            ops: [[]],
            open(){
              _vm.options.goodsCategory.show = true
            },
            close(){
              _vm.options.goodsCategory.show = false
            },
            def(){
              _vm.options.goodsCategory.text = "点击选择商品分类"
            },
            confirm(v){
              console.log("点击选择商品分类 :" ,v)
              _vm.condition.data.categoryId = v.value[0].id;
              _vm.options.goodsCategory.text = v.value[0].name;
              _vm.options.goodsCategory.close();
            }
          },
          /* 删除商品对话框 */
          deleteGoodsDialog: {
            deleteId: null,
            deleteIndex: -1,
            confirm(){
              if (service.check.isNull(_vm.options.deleteGoodsDialog.deleteId)) {
                _vm.$refs.popup.error("删除操作失败,请重试")
                return
              }
              _vm.deleteGoods(_vm.options.deleteGoodsDialog.deleteId,
                  _vm.options.deleteGoodsDialog.deleteIndex);
              _vm.$refs.deleteDialog.close();
            },
            open(deleteId,deleteIndex){
              _vm.options.deleteGoodsDialog.deleteId = deleteId;
              _vm.options.deleteGoodsDialog.deleteIndex = deleteIndex;
              _vm.$refs.deleteDialog.open();
            },
            close(){
              _vm.options.deleteGoodsDialog.deleteId = null;
              _vm.options.deleteGoodsDialog.deleteIndex = -1;
              _vm.$refs.deleteDialog.close();
            }
          }
        },
        /* 条件筛选对象 */
        condition:{
          show: false,
          open(){
            _vm.condition.show = true;
          },
          close(){
            _vm.condition.show = false;
          },
          data: {
            /* 区域id */
            regionId: '',
            /* 商品标题 */
            title: '',
            /* 分类id */
            categoryId: '',
            /* 创建时间 */
            createTime: {
              value:[],
              change(e){
                console.log("选中创建时间 : ", e)
              }
            }
          },
          def(){
            _vm.condition.data.regionId= ''
            _vm.condition.data.title = ''
            _vm.condition.data.categoryId = ''
            _vm.condition.data.createTime.value = []
            _vm.options.goodsCategory.def()
            _vm.condition.search();
          },
          search(){
            console.log("点击搜索 条件 : ", _vm.condition.data)
            _vm.condition.close();
            _vm.getList();
          }
        },
			};
		},
    methods: {
		  getList(){
		    let _t = this;
		    let data = {}
        data.pageNo = this.table.pageNo
        data.pageSize = this.table.pageSize
        // 如果有排序字段添加排序字段
        if(this.listSortPicker.sortKey !== null){
          data.sortKey = this.listSortPicker.sortKey;
          data.sort = this.listSortPicker.sort;
        }
        // 追加条件搜索 字段
        let cData = _t.condition.data;
        if(!service.check.isNull(cData.regionId)){
          data.regionId = cData.regionId;
        }
        if(!service.check.isNull(cData.title)){
          data.title = cData.title;
        }
        if(!service.check.isNull(cData.categoryId)){
          data.categoryId = cData.categoryId;
        }
        if(cData.createTime.value.length !== 0){
          data.createTimeScope = JSON.stringify(cData.createTime.value);
        }
        _t.table.loading = true
        this.$axios({
          url: "merchant/merchantVegetable/vegetableList",
          method: "post",
          data: data,
          header: {
            "Authorization": this.token,
            "Content-type": this.contentType,
            "type": "merchantsToken"
          },
        }).then(res => {
          console.log(" admin/merchantManage/vegetableList :  " ,res)
          if(res.code === 0){
            _t.table.pageNo = res.result.pageNo;
            _t.table.pageSize = res.result.pageSize;
            _t.table.total = res.result.total;
            if (res.result.list.length > 0){
              // 处理图像
              res.result.list = res.result.list.map(e => {
                if(!service.check.isNull(e.avatar) && !e.avatar.includes(_t.imgApi)){
                  e.avatar = _t.imgApi + e.avatar
                }
                if(!service.check.isNull(e.img)){
                  e.img = JSON.parse(e.img).map(e2 => {
                    if(!e2.includes(_t.imgApi)){
                      e2 = _t.imgApi + e2
                    }
                    return e2
                  })
                }
                return e
              });
            }
            _t.table.data = res.result.list
          }else{
            _t.$refs.popup.error(res.message)
          }
        })
        .finally(function () {
          _t.table.loading = false
        })
      },
      getCategoryList() {
		    let _t = this
        this.$axios({
          url: "system/sysCategory/listNoPage",
          method: "post",
          data:{
            type: 2
          },
          header: {
            "Authorization": this.token,
            "Content-type": this.contentType,
            "type": "merchantsToken"
          },
        }).then(res => {
          console.log(" system/sysCategory/listNoPage : " , res)
          if(res.code === 0){
            _t.options.goodsCategory.ops[0] = res.result;
          }
        });
      },

      /* 更改上下架状态 id 为商品id */
      updateStatus(id,index){
        let _t = this;
        this.$axios({
          url: "merchant/merchantVegetable/upOrDown",
          method: "post",
          data: {
            id: id
          },
          header: {
            "Authorization": this.token,
            "Content-type": this.contentType,
            "type": "merchantsToken"
          },
        }).then(res => {
          console.log(" merchant/merchantVegetable/upOrDown : " ,res)
          if(res.code === 0){
            _t.$refs.popup.success("操作成功")
            console.log(_t.table.data[index])
            _t.table.data[index].status  = _t.table.data[index].status === 0 ? -1 : 0;
          }else{
            _t.$refs.popup.error(res.message)
          }
        })
      },

      deleteGoods(deleteId,index){
        let _t = this;
        this.$axios({
          url: "merchant/merchantVegetable/remove",
          method: "post",
          data: {
            id: deleteId
          },
          header: {
            "Authorization": this.token,
            "Content-type": this.contentType,
            "type": "merchantsToken"
          },
        }).then(res => {
          console.log(" merchant/merchantVegetable/delete : " ,res)
          if(res.code === 0){
            _t.table.data.splice(index,1);
            _t.$refs.popup.success("操作成功");
          }else{
            _t.$refs.popup.error("删除操作失败 , " + res.message)
          }
        }).finally(() =>{
          _t.$refs.deleteDialog.close();
        })
      }
    },
    onLoad() {
      // 获取图像地址前缀
      this.imgApi = this.$reqConfig.URLIMAGE
      // 获取请求头类型
      this.contentType = this.$reqConfig.CONTENTTYPE + ";+charset=UTF-8"
      // 获取token
      this.token = uni.getStorageSync("merchantsToken").token
    },
    onShow(){
      this.getCategoryList()
      this.getList()
    }
	}
</script>

<style lang="scss">
.table-th-font{
  color: #1c6f5c;
}
/*表头样式*/
.uni-table-th {
  background-color: #eff8ff;
  border: 1px #EBEEF5 solid;
}
.uni-table-td {
  font-size: 15px !important;
}
.uni-fab__item-text {
  font-size: 24rpx !important;
}
.operation-btn{
  margin: 2rpx 4rpx;
}
#text-flow{
  display: -webkit-box; /*弹性伸缩盒子模型显示*/
  -webkit-box-orient: vertical; /*排列方式*/
  -webkit-line-clamp: 1; /*显示文本行数(这里控制多少行隐藏)*/
  overflow: hidden; /*溢出隐藏*/
}
</style>
